﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acms.Bll;
using Telerik.Web.UI;

public partial class Posts_Position : BasePostPage
{
    public override Role.Roles[] AllowedRoles
    {
        get { return new Role.Roles[]{Role.Roles.Developer, Role.Roles.ContentViewer, Role.Roles.ContentPublisher, Role.Roles.ContentEditor}; }
    }

    public Role.Roles[] EditRoles
    {
        get { return new Role.Roles[] { Role.Roles.Developer, Role.Roles.ContentPublisher, Role.Roles.ContentEditor }; }
    }

    public Role.Roles[] PublishRoles
    {
        get { return new Role.Roles[] { Role.Roles.Developer, Role.Roles.ContentPublisher}; }
    }

    private List<int> allowedTemplateIds = new List<int>();

    protected void Page_Load(object sender, EventArgs e)
    {
        tvMap.NodeDataBound += new Telerik.Web.UI.RadTreeViewEventHandler(tvMap_NodeDataBound);
        tvMap.NodeDrop += new Telerik.Web.UI.RadTreeViewDragDropEventHandler(tvMap_NodeDrop);
        if (!IsPostBack)
        {
            if (PostId > 0)
            {
                ucHeader.Visible = true;
                accordianTitle.Visible = false;
            }
            else
            {
                accordianTitle.Visible = true;
                pnlWrapper.CssClass = "";
                ucHeader.Visible = false;
            }

            dsSiteMap.SiteId = AcmsContext.SiteId;
            dsSiteMap.CurrentSiteVersion = base.SelectedVersion;

            if (base.SelectedVersion == null)
            {
                lblTitle.Text = "Pending Positions";
            }
            else if (base.SelectedVersion.Value < DateTime.Now)
            {
                lblTitle.Text = "Live Positions";
            }
            else
            {
                lblTitle.Text = string.Format("{0:dd MMM yyyy HH:mm} Positions", base.SelectedVersion.Value);
            }
            if (CurrentPost != null)
            {
                List<Template> templates = Template.GetAllByChildTemplateId(CurrentPost.TemplateId);
                foreach (Template t in templates)
                {
                    allowedTemplateIds.Add(t.Id);
                }
            }
        }
    }

    void tvMap_NodeDrop(object sender, RadTreeNodeDragDropEventArgs e)
    {
        List<Post> postsToUpdate = new List<Post>();
        //changing parent node
        int movedId = int.Parse(e.SourceDragNode.Value);
        Post moved = Post.GetById(AcmsContext.SiteId, movedId, base.SelectedVersion);
        if (e.DropPosition != RadTreeViewDropPosition.Over && e.DestDragNode.ParentNode == null)
        {
            //dont allow drop bellow or above home page node
            return;
        }
        else if (e.DropPosition == RadTreeViewDropPosition.Over && e.DestDragNode != e.SourceDragNode.Parent)
        {
            if (e.DestDragNode.Nodes.Count > 0)
            {
                int siblingId = int.Parse(e.DestDragNode.Nodes[e.DestDragNode.Nodes.Count - 1].Value);
                Post sibling = Post.GetById(AcmsContext.SiteId, siblingId, base.SelectedVersion);
                moved.ParentGuid = sibling.ParentGuid;
                moved.Sequence = sibling.Sequence + 1;
                postsToUpdate.Add(moved);
            }
            else
            {
                int parentId = int.Parse(e.DestDragNode.Value);
                Post parent = Post.GetById(AcmsContext.SiteId, parentId, base.SelectedVersion);
                moved.ParentGuid = parent.PostGuid;
                moved.Sequence = 0;
                postsToUpdate.Add(moved);
            }
            //ensure parent is open
            e.DestDragNode.Expanded = true;
        }
        else
        {
            RadTreeNode currentNode= e.DestDragNode;
            int currentId = int.Parse(currentNode.Value);
            Post current = Post.GetById(AcmsContext.SiteId, currentId, SelectedVersion);

            if (e.SourceDragNode.Parent != e.DestDragNode.Parent)
            {
                //changing parent position
                moved.ParentGuid = current.ParentGuid;
            }

            postsToUpdate.Add(moved);
            //sequences
            if (e.DropPosition == RadTreeViewDropPosition.Above)
            {
                moved.Sequence = current.Sequence;
                current.Sequence++;
                postsToUpdate.Add(current);
            }
            else
            {
                moved.Sequence = current.Sequence + 1;
            }

            while (currentNode.Next != null)
            {
                currentNode = currentNode.Next;
                if (currentNode != e.SourceDragNode)
                {
                    currentId = int.Parse(currentNode.Value);
                    current = Post.GetById(AcmsContext.SiteId, currentId, SelectedVersion);
                    current.Sequence++;
                    postsToUpdate.Add(current);
                }
            }
        }

        if (postsToUpdate.Count > 1)
        {
            postsToUpdate[0].BeginTransaction();
        }

        foreach(Post p in postsToUpdate)
        {
            if (p.TransactionKey != postsToUpdate[0].TransactionKey)
            {
                p.UseTransaction(postsToUpdate[0].TransactionKey);
            }
            p.RequiresPublishing = true;
            p.Update();
        }

        if (postsToUpdate.Count > 1)
        {
            postsToUpdate[0].CommitTransaction();
        }

        if (postsToUpdate.Count > 0)
        {
            if (e.SourceDragNode.ParentNode == e.DestDragNode.ParentNode)
            {
                e.SourceDragNode.ParentNode.Nodes.Remove(e.SourceDragNode);
            }
            if (e.DropPosition == RadTreeViewDropPosition.Over)
            {
                e.DestDragNode.Nodes.Add(e.SourceDragNode);
            }
            else if(e.DropPosition == RadTreeViewDropPosition.Above)
            {
                e.DestDragNode.InsertBefore(e.SourceDragNode);
            }
            else if (e.DropPosition == RadTreeViewDropPosition.Below)
            {
                e.DestDragNode.InsertAfter(e.SourceDragNode);
            }
        }
    }

    void tvMap_NodeDataBound(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        Post dataSource = e.Node.DataItem as Post;

        //if the home page cant move it
        if (e.Node.ParentNode == null)
        {
            e.Node.CssClass = "fixed";
            e.Node.AllowDrag = false;
            e.Node.AllowDrop = true;
        }
        //if post we are looking at then allow drag unless locked
        else if (dataSource.Id == base.PostId)
        {
            e.Node.Selected = true;
            e.Node.Expanded = false;
            e.Node.ExpandParentNodes();
            if (!dataSource.DeveloperLocked)
            {
                e.Node.AllowDrag = true;
            }
            else
            {
                e.Node.CssClass = "fixed";
                e.Node.AllowDrag = User.HasRole(Role.Roles.Developer);
            }
        }
        //if parent of selected node
        else if(CurrentPost != null && dataSource.PostGuid == CurrentPost.ParentGuid)
        {
            e.Node.AllowDrag = true;
            e.Node.AllowDrop = true;
            e.Node.NavigateUrl = base.AppendQueryStringParameters("?", dataSource.Id, SelectedVersion);
        }
        //if not then normal post
        else
        {
            e.Node.AllowDrag = false;
            if(dataSource.DeveloperLocked)
                e.Node.CssClass = "fixed";
            //if (CurrentPost != null && CurrentPost.DeveloperLocked)
            //    e.Node.AllowDrop = false;
            //else
                e.Node.AllowDrop = allowedTemplateIds.Contains(dataSource.TemplateId);
            if (!e.Node.AllowDrop)
                e.Node.ForeColor = System.Drawing.Color.LightGray;
            e.Node.NavigateUrl = base.AppendQueryStringParameters("?", dataSource.Id, SelectedVersion);
            if (e.Node.ParentNode == null || e.Node.ParentNode.ParentNode == null)
            {
                e.Node.ExpandParentNodes();
            }
        }

        /*if (e.Node.Value == base.PostId.ToString()) 
        {
            e.Node.Selected = true;
            e.Node.Expanded = false;
            e.Node.ExpandParentNodes();
        }

        if (dataSource != null)
        {
            if(dataSource.Id == base.PostId && dataSource.DeveloperLocked)
            {
                if (!User.HasRole(Role.Roles.Developer))
                {
                    e.Node.AllowDrag = false;
                }
                e.Node.CssClass = "fixed";
            }
        }*/
    }

    public override void GetBreadCrumbs(BaseMasterPage.BreadCrumbCollection breadcrumbs)
    {
        base.GetBreadCrumbs(breadcrumbs);
        breadcrumbs.Add("Position");
    }
}
